<template>
	<div
		class="page"
		style="
			padding: 20px 20px 0px 20px;
			width: 80%;
			margin-left: 50%;
			left: -600px;
			position: relative;
		"
	>
		<div class="login-wrap">
			<el-row>
				<el-col style="width: 100%; text-align: center; line-height: 60px">
					开放平台登陆
				</el-col>
			</el-row>
			<el-form
				ref="form"
				:model="form"
				label-width="80px"
				status-icon
				:rules="rules"
			>
				<el-form-item label="账号" prop="username">
					<el-input v-model="form.username" size="lager"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
						type="password"
						v-model="form.password"
						autocomplete="off"
						size="medium"
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm()"> 登录 </el-button>
					<el-button @click="register()"> 注册 </el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
import request from "@/utils/request";
import md5 from "js-md5";
import { useUserStore } from "@/stores/userInfo";

export default {
	components: {},
	data() {
		return {
			form: {
				username: "",
				password: "",
			},
			rules: {
				username: [{ required: true, message: "请输入账号", trigger: "blur" }],
				password: [{ required: true, message: "请输入密码", trigger: "blur" }],
			},
		};
	},
	methods: {
		submitForm() {
			this.$refs["form"].validate((valid) => {
				let that = this;
				if (valid) {
					request({
						url: "/login",
						method: "post",
						data: {
							username: this.form.username,
							password: md5(this.form.password),
						},
					}).then(async (res) => {
						if (res.code === 200) {
							localStorage.setItem("token", res.token);

							that.$message({
								type: "success",
								message: "登录成功",
							});
							let userInfo = await that.getUserInfo();
							const store = useUserStore();
							store.userInfo = userInfo;

							localStorage.setItem("userInfo", JSON.stringify(userInfo));
							that.$router.push("/appInfo");
						}
					});
				} else {
					console.log("error submit!!");
					return false;
				}
			});
		},
		register() {
			this.$router.push("/register");
		},
		async getUserInfo() {
			let res = await request({
				url: "/user/profile",
				method: "get",
			});
			return res.data;
		},
	},
};
</script>
<style lang="scss" scoped>
.page {
	display: flex;
	justify-content: center;

	.login-wrap {
		margin-top: 150px;
		.title {
			color: #248df9;
			text-align: center;
		}
	}
}
</style>
